<?php
/**
 * 编辑器server
 * @author yupoxiong<i@yufuping.com>
 */

namespace app\admin\controller;

use think\Request;
use think\Db;

class FachatController extends Controller
{
    /*
     * 聊天列表
     * */
    public function index(Request $request)
    {
        $param = $request->param();
        $fromUserId = $param['fromUserId']??'';
        $toUserId = $param['toUserId']??'';
        $this->assign('fromUserId', $fromUserId);
        $this->assign('toUserId', $toUserId);
        $this->assign('data', []);
        return $this->fetch();
    }


    public function lists(Request $request)
    {
        $param = $request->param();
        $fromUserId = $param['fromUserId'];
        $from_me_uid = $param['from_me_uid'];
        $toUserId = $param['toUserId'];
        $to_me_uid = $param['to_me_uid'];
        $start_time = $param['start_time'];
        $end_time = $param['end_time'];

        $where = "";
        if ($fromUserId) {
            $where .= " and  fromUserId='$fromUserId'";
        }
        if ($from_me_uid) {
            $where .= " and  from_me_uid='$from_me_uid'";
        }
        if ($toUserId) {
            $where .= " and  toUserId='$toUserId'";
        }
        if ($to_me_uid) {
            $where .= " and  to_me_uid='$to_me_uid'";
        }
        if ($start_time) {
            $start = strtotime($start_time) * 1000;
            $where .= " and  timestamp>='$start'";
        }
        if ($end_time) {
            $end = strtotime($end_time) * 1000;
            $where .= " and  timestamp<='$end'";
        }

        $from_one = 0;
        $to_one = 0;
        if (($fromUserId) || ($from_me_uid)) {
            if ((empty($toUserId)) && (empty($to_me_uid))) {
                $from_one = 1;
                $to_one = 0;
            } else {
                $from_one = 1;
                $to_one = 1;
            }
        }

        if (($toUserId) || ($to_me_uid)) {
            if ((empty($fromUserId)) && (empty($from_me_uid))) {
                $to_one = 1;
                $from_one = 0;
            } else {
                $from_one = 1;
                $to_one = 1;
            }
        }

        if ($from_one || $to_one) {
            $list = Db::query("select from_me_sex,to_me_sex,fromUserId,from_me_uid,toUserId,to_me_uid,max(timestamp) from fa_rong_msg m where channelType='PERSON'  $where GROUP BY from_me_uid,to_me_uid order by max(timestamp) desc");

            $group = Db::table("fa_rong_msg")->field("fromUserId,from_me_uid,toUserId,to_me_uid")->where("channelType='PERSON'")->group("from_me_uid,to_me_uid")->select();

            $array = [];
            foreach ($group as $k => &$v) {
                if (!(in_array($v['fromUserId'], $array))) {
                    array_push($array, $v['fromUserId']);
                }
                if (!(in_array($v['toUserId'], $array))) {
                    array_push($array, $v['toUserId']);
                }
            }

            $total = count($array);
            $member = Db::table("fa_member")->field("member_id,me_sex")->where("member_id", "in", $array)->select();
            $man = 0;
            $woman = 0;
            foreach ($member as $k => &$v) {
                if ($v['me_sex'] == 1) {
                    $man++;
                }
                if ($v['me_sex'] == 2) {
                    $woman++;
                }
            }

            foreach ($list as $k => &$v) {
                $v['from_member'] = Db::table("fa_member")->where(["member_id" => $v['fromUserId']])->field("member_id,me_nick_name,me_img,me_sex")->find();
                $v['to_member'] = Db::table("fa_member")->where(["member_id" => $v['toUserId']])->field("member_id,me_nick_name,me_img,me_sex")->find();
            }


            $from_user = '';
            $to_user = '';

            $from = [];
            $from_total = 0;
            $from_nan = 0;
            $from_nv = 0;

            $to = [];
            $to_total = 0;
            $to_nan = 0;
            $to_nv = 0;

            foreach ($list as $k => &$v) {
                if ($v['from_member']['me_sex'] == 1) {
                    if (!in_array($v['from_me_uid'], $from)) {
                        $from_nan++;
                    }
                    $from_xingbie = '男';
                    $from_color = 'green';
                } elseif ($v['from_member']['me_sex'] == 2) {
                    if (!in_array($v['from_me_uid'], $from)) {
                        $from_nv++;
                    }
                    $from_xingbie = '女';
                    $from_color = 'red';
                } else {
                    $from_xingbie = '';
                    $from_color = 'black';
                }
                if ($v['to_member']['me_sex'] == 1) {
                    if (!in_array($v['to_me_uid'], $to)) {
                        $to_nan++;
                    }
                    $to_xingbie = '男';
                    $to_color = 'green';
                } elseif ($v['to_member']['me_sex'] == 2) {
                    if (!in_array($v['to_me_uid'], $to)) {
                        $to_nv++;
                    }
                    $to_xingbie = '女';
                    $to_color = 'red';
                } else {
                    $to_xingbie = '';
                    $to_color = 'black';
                }

                if (!in_array($v['from_me_uid'], $from)) {
                    $from_total++;
                }
                if (!in_array($v['to_me_uid'], $to)) {
                    $to_total++;
                }
                array_push($from, $v['from_me_uid']);
                array_push($to, $v['to_me_uid']);


                $time = date('Y-m-d H:i:s', ($v['max(timestamp)'] * 0.001));
                $from_me_sex_max = $v['from_me_sex'];
                if($from_me_sex_max==1){
                    $from_me_sex_max = '男';
                }elseif($from_me_sex_max==2){
                    $from_me_sex_max = '女';
                }else{
                    $from_me_sex_max = '未知';
                }

                $time2 = '';
                $toUserId2 = $v['toUserId'];
                $to_me_sex_max = '';

                $fa_rong_msg = Db::query("select from_me_sex,to_me_sex,fromUserId,from_me_uid,toUserId,to_me_uid,max(timestamp) from fa_rong_msg m where channelType='PERSON'  and fromUserId='$toUserId2' order by max(timestamp) desc");
                if($fa_rong_msg){
                    $time2 =  date('Y-m-d H:i:s',$fa_rong_msg[0]['max(timestamp)']* 0.001);
                    $to_me_sex_max = $fa_rong_msg[0]['from_me_sex'];
                    if($to_me_sex_max==1){
                        $to_me_sex_max = '男';
                    }elseif($to_me_sex_max==2){
                        $to_me_sex_max = '女';
                    }else{
                        $to_me_sex_max = '未知';
                    }
                }



                $today = strtotime(date('Y-m-d'));
                $end_totday = $today + 86400;

                if ($from_one == 1) {
                    if ($k == 0) {
                        $from_action = $this->from_action($v, $today, $end_totday);
                    }
                } else {
                    $from_action = $this->from_action($v, $today, $end_totday);
                }


                if ($to_one == 1) {
                    if ($k == 0) {
                        $to_action = $this->to_action($v, $today, $end_totday);
                    }
                } else {
                    $to_action = $this->to_action($v, $today, $end_totday);
                }

                $fromUserId = $v['fromUserId'];
                $toUserId = $v['toUserId'];

                $from_user .= '<tr >
                        <td><img style="width: 50px;height: 50px;border-radius: 50px" src="' . $v['from_member']['me_img'] . '"></td>
                        <td><div style="color: ' . $from_color . '" >' . $v['from_member']['me_nick_name'] . '</div></td>
                        <td>' . $v['from_member']['member_id'] . '</td>
                        <td style="display: none"><span style="color: ' . $from_color . '">' . $from_xingbie . '</span></td>
                        <td>性别'.$from_me_sex_max.'：' . $time . '<br> 性别'.$to_me_sex_max.'：'.$time2.'</td>
                        <td style="display: none">' . $from_action['from_tixian_time'] . '</td>
                        <td style="display: none">' . $from_action['from_tixian_amount'] . '</td>
                        <td style="display: none">' . $from_action['from_tixian_all'] . '</td>
                        <td>' . $from_action['from_cz_time'] . '</td>
                        <td>' . $from_action['from_cz_amount'] . '</td>
                        <td>' . $from_action['from_cz_all'] . '</td>
                        <td>' . $from_action['from_child_today_count'] . '</td>
                        <td>' . $from_action['from_child_total_count'] . '</td>
                        <td style="cursor: pointer" onclick="info(' . $fromUserId . ',' . $toUserId . ')"> 查看聊天记录 </td>

                    </tr>';

                $to_user .= '<tr >
                        <td><img style="width: 50px;height: 50px;border-radius: 50px" src="' . $v['to_member']['me_img'] . '"></td>
                        <td><div style="color: ' . $to_color . '" >' . $v['to_member']['me_nick_name'] . '</div></td>
                        <td>' . $v['to_member']['member_id'] . '</td>
                        <td style="display: none"><span style="color: ' . $to_color . '">' . $to_xingbie . '</span></td>
                        <td>性别'.$from_me_sex_max.'：' . $time . '<br> 性别'.$to_me_sex_max.'：'.$time2.'</td>
                        <td style="display: none">' . $to_action['to_tixian_time'] . '</td>
                        <td style="display: none">' . $to_action['to_tixian_amount'] . '</td>
                        <td style="display: none">' . $to_action['to_tixian_all'] . '</td>
                        <td>' . $to_action['to_cz_time'] . '</td>
                        <td>' . $to_action['to_cz_amount'] . '</td>
                        <td>' . $to_action['to_cz_all'] . '</td>
                        <td>' . $to_action['to_child_today_count'] . '</td>
                        <td>' . $to_action['to_child_total_count'] . '</td>
                        <td style="cursor: pointer" onclick="info(' . $fromUserId . ',' . $toUserId . ')"> 查看聊天记录 </td>
                    </tr>';
            }

            echo json_encode(['total' => $total, 'man' => $man, 'woman' => $woman,
                'from_total' => $from_total, 'from_nan' => $from_nan, 'from_nv' => $from_nv, 'to_total' => $to_total, 'to_nan' => $to_nan, 'to_nv' => $to_nv, 'from_user' => $from_user, 'to_user' => $to_user]);
            exit;
        } else {
            exit;
        }
    }


    public function from_action($v, $today, $end_totday)
    {
        $from_zwithdrawal_order = Db::table("fa_zwithdrawal_order")->field("add_time,total_withdrawal")->where(['member_id' => $v['fromUserId']])->order("id desc")->limit(1)->find();
        $from_tixian_time = '';
        $from_tixian_amount = 0;
        $from_tixian_all = Db::table("fa_zwithdrawal_order")->where(['member_id' => $v['fromUserId']])->sum('total_withdrawal');
        if ($from_zwithdrawal_order) {
            $from_tixian_time = date('Y-m-d H:i:s', $from_zwithdrawal_order['add_time']);
            $from_tixian_amount = $from_zwithdrawal_order['total_withdrawal'];
        }


        $from_cz_finance = Db::table("fa_finance")->field("add_time,money")->where(['member_id' => $v['fromUserId']])->where("type", "in", "2,7,11,19,21")->order("id desc")->limit(1)->find();
        $from_cz_time = '';
        $from_cz_amount = 0;
        $from_cz_all = Db::table("fa_finance")->where(['member_id' => $v['fromUserId']])->where("type", "in", "2,7,11,19,21")->sum('money');
        if ($from_cz_finance) {
            $from_cz_time = date('Y-m-d H:i:s', $from_cz_finance['add_time']);
            $from_cz_amount = $from_cz_finance['money'];
        }

        $from_child_today_count = Db::table("fa_member")->where(["me_parent" => $v['fromUserId']])
            ->where("me_add_time>=$today")->where("me_add_time<=$end_totday")->count();
        $from_child_total_count = Db::table("fa_member")->where(["me_parent" => $v['fromUserId']])
            ->count();

        return ['from_tixian_time' => $from_tixian_time, 'from_tixian_amount' => $from_tixian_amount,
            'from_tixian_all' => $from_tixian_all, 'from_cz_time' => $from_cz_time,
            'from_cz_amount' => $from_cz_amount, 'from_cz_all' => $from_cz_all,
            'from_child_today_count' => $from_child_today_count, 'from_child_total_count' => $from_child_total_count];

    }


    public function to_action($v, $today, $end_totday)
    {
        $to_zwithdrawal_order = Db::table("fa_zwithdrawal_order")->field("add_time,total_withdrawal")->where(['member_id' => $v['toUserId']])->order("id desc")->limit(1)->find();
        $to_tixian_time = '';
        $to_tixian_amount = 0;
        $to_tixian_all = Db::table("fa_zwithdrawal_order")->where(['member_id' => $v['toUserId']])->sum('total_withdrawal');

        if ($to_zwithdrawal_order) {
            $to_tixian_time = date('Y-m-d H:i:s', $to_zwithdrawal_order['add_time']);
            $to_tixian_amount = $to_zwithdrawal_order['total_withdrawal'];
        }

        $to_cz_finance = Db::table("fa_finance")->field("add_time,money")->where(['member_id' => $v['toUserId']])->where("type", "in", "2,7,11,19,21")->order("id desc")->limit(1)->find();
        $to_cz_time = '';
        $to_cz_amount = 0;
        $to_cz_all = Db::table("fa_finance")->where(['member_id' => $v['toUserId']])->where("type", "in", "2,7,11,19,21")->sum('money');
        if ($to_cz_finance) {
            $to_cz_time = date('Y-m-d H:i:s', $to_cz_finance['add_time']);
            $to_cz_amount = $to_cz_finance['money'];
        }

        $to_child_today_count = Db::table("fa_member")->where(["me_parent" => $v['toUserId']])
            ->where("me_add_time>=$today")->where("me_add_time<=$end_totday")->count();
        $to_child_total_count = Db::table("fa_member")->where(["me_parent" => $v['toUserId']])
            ->count();

        return ['to_tixian_time' => $to_tixian_time, 'to_tixian_amount' => $to_tixian_amount,
            'to_tixian_all' => $to_tixian_all, 'to_cz_time' => $to_cz_time,
            'to_cz_amount' => $to_cz_amount, 'to_cz_all' => $to_cz_all,
            'to_child_today_count' => $to_child_today_count, 'to_child_total_count' => $to_child_total_count];
    }

    public function convertMilliseconds($milliseconds)
    {
        $seconds = intval(substr($milliseconds, 0, -3));
        $date = date("Y-m-d H:i:s", $seconds);
        return $date;
    }

    public function info(Request $request)
    {
        $param = $request->param();
        $fromUserId = $param['fromUserId'];
        $toUserId = $param['toUserId'];

        $fromMember = Db::table("fa_member")->where(["member_id" => $fromUserId])->find();
        $toMember = Db::table("fa_member")->where(["member_id" => $toUserId])->find();

        if($fromMember){
            $fromMember['me_status_time_word'] = '-';

            if($fromMember['me_status']==1){
                $fromMember['me_status_word'] =  '正常';
                $fromMember['me_status_time_word'] = '未封禁';
            }elseif($fromMember['me_status']==2){
                $fromMember['me_status_word'] = '封禁';
                if ($fromMember['me_status_time'] != -1 && $fromMember['me_status_time'] != 0) {
                    $fromMember['me_status_time_word'] = date('Y-m-d H:i:s', $fromMember['me_status_time']);
                } else {
                    $fromMember['me_status_time_word'] = '永久';
                }
            }else{
                $fromMember['me_status_word'] =  '正常';
                $fromMember['me_status_time_word'] = '未封禁';
            }
        }else{
            $fromMember['me_status_word'] =  '正常';
            $fromMember['me_status_time_word'] = '未封禁';
        }



        if($toMember) {
            $toMember['me_status_time_word'] = '-';
            if ($toMember['me_status'] == 1) {
                $toMember['me_status_word'] = '正常';
                $toMember['me_status_time_word'] = '未封禁';
            } elseif ($toMember['me_status'] == 2) {
                $toMember['me_status_word'] = '封禁';
                if ($toMember['me_status_time'] != -1 && $toMember['me_status_time'] != 0) {
                    $toMember['me_status_time_word'] = date('Y-m-d H:i:s', $toMember['me_status_time']);
                } else {
                    $toMember['me_status_time_word'] = '永久';
                }
            } else {
                $toMember['me_status_word'] = '正常';
                $toMember['me_status_time_word'] = '未封禁';
            }
        }else{
            $toMember['me_status_word'] = '正常';
            $toMember['me_status_time_word'] = '未封禁';
        }




        $this->assign('fromUserId', $fromUserId);
        $this->assign('toUserId', $toUserId);
        $this->assign('from', $fromMember);
        $this->assign('to', $toMember);
        $this->assign('fromMember', $fromMember['me_nick_name']??'');
        $this->assign('toMember', $toMember['me_nick_name']??'');
        $this->assign('from_me_uid', $fromMember['me_uid']??'');
        $this->assign('to_me_uid', $toMember['me_uid']??'');
        return $this->fetch();
    }

    public function ajax_info(Request $request)
    {
        $param = $request->param();
        $fromUserId = $param['fromUserId'];
        $toUserId = $param['toUserId'];

        $page = input('page') ? input('page') : 1;
        $pagesize = input('pagesize') ? input('pagesize') : 50;
        $where = ["channelType"=>'PERSON'];

        if (($fromUserId) && ($toUserId)) {

            //开始时间
            $timeBegin = input('timeBegin') ? input('timeBegin') : "";
            //结束时间
            $timeEnd = input('timeEnd') ? input('timeEnd') : "";
            if (!empty($timeBegin) && !empty($timeEnd)) {
                $timeBegin2 = $timeBegin * 1000;
                $timeEnd2 = $timeEnd * 1000;
                $where['a.timestamp'] = ['between', [$timeBegin2, $timeEnd2]];
            }


            $sysh_member_from = Db::table("fa_member")->field("member_id,me_nick_name")->where("member_id=$fromUserId")->find();
            $fromMember = $sysh_member_from["me_nick_name"];
            $from_member_id = $sysh_member_from["member_id"];


            $sysh_member_to = Db::table("fa_member")->field("member_id,me_nick_name")->where("member_id=$toUserId")->find();
            $toMember = $sysh_member_to["me_nick_name"];
            $to_member_id = $sysh_member_to["member_id"];


            $list = Db::table("fa_rong_msg")
                ->alias('a')->field("a.id,a.fromUserId,a.toUserId,a.timestamp,a.content,a.voice_to_text,a.objectName,a.from_me_sex sex,a.to_me_sex sex2")
                ->where($where)->where("(a.fromUserId=$from_member_id and a.toUserId=$to_member_id) or (a.fromUserId=$to_member_id and a.toUserId=$from_member_id)")
                ->page($page, $pagesize)
                ->order("a.id desc")
                //->fetchSql(true)
                ->select();
            //dump($list);
            //die;

            foreach ($list as $k => &$v) {
                $v['voice_to_text'] = empty($v['voice_to_text'])?'未识别':$v['voice_to_text'];

                $v['from_member'] = Db::table("fa_member")->where(['member_id' => $v['fromUserId']])->field("member_id,me_uid,me_nick_name,me_img")->find();
                if ($v['sex'] == 1) {
                    $v['from_member']['xingbie'] = '男';
                } elseif ($v['sex'] == 2) {
                    $v['from_member']['xingbie'] = '女';
                } else {
                    $v['from_member']['xingbie'] = '未知';
                }


                $v['to_member'] = Db::table("fa_member")->where(['member_id' => $v['toUserId']])->field("member_id,me_uid,me_nick_name,me_img")->find();
                if ($v['sex2'] == 1) {
                    $v['to_member']['xingbie'] = '男';
                } elseif ($v['sex2'] == 2) {
                    $v['to_member']['xingbie'] = '女';
                } else {
                    $v['to_member']['xingbie'] = '未知';
                }

                $v['shijian'] = $this->convertMilliseconds($v['timestamp']);

            }

            $count = Db::table("fa_rong_msg")
                ->alias('a')->field("a.id")
                ->where($where)
                ->count();

            array_multisort(array_column($list, 'id'), SORT_ASC, $list);

            return json(['code' => '200', 'msg' => '查询成功', 'total' => $count, 'data' => $list, 'fromMember' => $fromMember, 'toMember' => $toMember]);
        } else {
            return json(['code' => '400', 'msg' => '请输入发送方用户号与接收方用户号', 'total' => 0, 'data' => [], 'fromMember' => '', 'toMember' => '']);
        }

    }

}